<?php
namespace Admin\Model;
use Think\Model\RelationModel;

class ClassModel extends RelationModel {

	protected $_validate = array(
		array('id', 'require', 'id不能为空！'),
		array('grade', 'require', '年级不能为空！'),
		array('major_id', 'require', '专业不能为空！', 1),
		array('class', 'require', '班号不能为空！'),
	);

	protected $_auto = array(
		array('grade', 'intval', 3, 'function'),
		array('major_id', 'intval', 3, 'function'),
		array('class', 'intval', 3, 'function'),
	);

	protected $_link = array(
		'major'	=> array(
			'mapping_type'	=> self::BELONGS_TO,
			'class_name'	=> 'Major',
			'foreign_key'	=> 'major_id',
		),
		'students'	=> array(
		    'mapping_type'  => self::HAS_MANY,
		    'class_name'    => 'Student',
		    'foreign_key'   => 'class_id',
		),
	);

	public function checkUnique($class) {
		$map['grade'] = (int)$class['grade'];
		$map['major_id'] = (int)$class['major_id'];
		$map['class'] = (int)$class['class'];
		return !$this->where($map)->find();
	}

	public function hasChildObj($id) {
		$result = $this->where(array('id' => $id))->relation('students')->find();
		if($result['students']) {
			$this->error = '该学院下面还存在学生未删除，请先删除这些学生！';
			return true;
		}
		return false;
	}

}
